<template>
  <div>
    <div class="toolbar-box">
      <el-input placeholder="输入关键字进行过滤" v-model="filterTreeText" />
    </div>
    <el-scrollbar style="height: 400px">
      <el-tree node-key="id" class="filter-tree" highlight-current :props="treeProps" :data="tdata"
        v-loading.lock="loading" element-loading-text="拼命加载中" :expand-on-click-node="true"
        @node-click="treeNodeClickEvent" @node-expand="treeNodeExpandEvent" @node-collapse="treeNodeCollapseEvent"
        :filter-node-method="filterTreeNode" ref="treeRef">
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <icon-svg v-if="data.attributes && data.attributes.icon" :name="data.attributes.icon"></icon-svg>
            <span>{{ node.label }}&nbsp;&nbsp;</span>
          </span>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import { ref, watch, reactive, onMounted } from "vue";

import { ElTree } from 'element-plus';

// 是否正在加载
const loading = ref(true);

// 部门树数据
const tdata = ref([]);

// 展开节点
const expandedKeys = ref([]);

// 部门树默认属性
const treeProps = reactive({
  label: "name",
  children: "children",
})

// 菜单树过滤文本
const filterTreeText = ref("");

// 部门树引用
const treeRef = ref<InstanceType<typeof ElTree>>();

// 父级组件的自定义事件
const emit = defineEmits(['node-click']);

// 监听查询内容变化
watch(filterTreeText, (n, o) => {
  treeRef.value!.filter(n)
});

// 组件挂载完成后执行
onMounted(() => {
  loading.value = true;
  http
    .post({
      url: "/product/category/mtree",
    }).then(({ data }) => {
      if (http.success(data)) {
        tdata.value = data.body;
      }
      loading.value = false;
    });
});

// 分类节点点击事件
const treeNodeClickEvent = (data) => {
  emit("node-click", data);
};

// 树展开事件
const treeNodeExpandEvent = (data) => {
  if (expandedKeys.value.indexOf(data.id) === -1) {
    expandedKeys.value.push(data.id);
  }
};

// 树关闭事件
const treeNodeCollapseEvent = (data) => {
  let texpandedKeys = expandedKeys.value;
  for (let i = 0; i < texpandedKeys.length; i++) {
    if (texpandedKeys[i] === data.id) {
      texpandedKeys.splice(i, 1);
      expandedKeys.value = texpandedKeys;
    }
    let children = data.children;
    if (children && children.length > 0) {
      for (let h = 0; h < children.length; h++) {
        treeNodeCollapseEvent(children[h]);
      }
    }
  }
};

// 过滤菜单
const filterTreeNode = (value, data) => {
  if (!value) {
    return true;
  }
  return data.name.indexOf(value) !== -1;
};
</script>

<style lang="scss" scoped>
.toolbar-box {
  margin: 10px 0;
}
</style>